package com.tju.resource.oauth.controller.doc;

import com.tju.resource.common.ServiceException;
import com.tju.resource.model.DocContent;
import com.tju.resource.business.doc.DocUserPermService;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.tool.tool.ChineseExceptionUtils;
import com.tju.resource.tool.tool.ClientParameters;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.security.Principal;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 文档
 *
 * @Author CLS
 * @Date 2022/2/28 10:49
 */
@Slf4j
@RestController
@RequestMapping("doc")
public class DocController {

    @Autowired
    private ChineseExceptionUtils zh_ch;

    @Autowired
    private DocUserPermService docUserPermService;

    @PostMapping("docData")
    public Result<Object> docData(@RequestBody Map<String, Object> map, Principal principal) {
        return Optional.of(map)
                .filter(n -> (n.get("logInName") != null && n.get("parentMenu") != null))
                .map(n -> docUserPermService.docData((String) n.get("logInName"), n.get("parentMenu")))
                .orElseThrow(() -> new ServiceException(zh_ch.MissingParameters));
    }

    /*查询*/
    @PostMapping("/getComputerFile")
    @PreAuthorize("hasAuthority('sys:manage:doc:list')")
    public Result<Object> getComputerFile(@RequestBody ClientParameters parameters) {
        return Optional.ofNullable(parameters)
                .filter(p -> (p.getLimit() != 0))
                .map(p -> docUserPermService.getComputerFile(parameters))
                .orElseThrow(() -> new ServiceException(zh_ch.QueryFailed));
    }

    /*添加*/
    @ResponseBody
    @RequestMapping("/addComputerFile")
    @PreAuthorize("hasAuthority('sys:manage:doc:add')")
    public Result<Object> addComputerFile(@Valid DocContent data, BindingResult result, @RequestParam("file") MultipartFile file) {
        if (result.hasErrors()) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        } else {
            return Optional.ofNullable(file)
                    .filter(f -> (!file.isEmpty()))
                    .map(f -> docUserPermService.addComputerFile(data, file))
                    .orElseThrow(() -> new ServiceException(zh_ch.UploadFailed));
        }
    }

    /**
     * 重定向修改
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:manage:doc:edit')")
    @RequestMapping(value = "/uploadFileVerification")
    public Result<Object> uploadSwingCardimg(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 判断请求是否包含文件
            if (ServletFileUpload.isMultipartContent(request)) {
                //包含文件，请求转发
                request.getRequestDispatcher("updDocumentationFile").forward(request, response);
            } else {
                //不含文件,请求转发
                request.getRequestDispatcher("updComputerFile").forward(request, response);
            }
        } catch (Exception e) {
            throw new ServiceException(zh_ch.FailToEdit);
        }
        return null;
    }

    /*修改文档*/
    @PostMapping("/updComputerFile")
    public Result<Object> updComputerFile(@Valid @RequestBody DocContent data, BindingResult result) {
        if (result.hasErrors()) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        } else {
            return Optional.ofNullable(data)
                    .filter(d -> d.getId() != null)
                    .map(d -> docUserPermService.updComputerFile(data, null))
                    .orElseThrow(() -> new ServiceException(zh_ch.FailToEdit));
        }
    }

    /*修改文档和文件*/
    @PostMapping("/updDocumentationFile")
    public Result<Object> updDocumentationFile(@Valid DocContent data, BindingResult result, @RequestParam(value = "file") MultipartFile file) {
        if (result.hasErrors()) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        } else {
            return Optional.ofNullable(data)
                    .filter(d -> d.getId() != null)
                    .map(d -> docUserPermService.updComputerFile(data, file))
                    .orElseThrow(() -> new ServiceException(zh_ch.FailToEdit));
        }
    }

    /*删除*/
    @PostMapping("/delComputerFile")
    @PreAuthorize("hasAuthority('sys:manage:doc:delete')")
    public Result<Object> delComputerFile(@RequestBody DocContent docContent) {
        return Optional.ofNullable(docContent)
                .filter(d -> d.getId() != null && d.getImgName() != null)
                .map(d -> docUserPermService.delComputerFile(docContent))
                .orElseThrow(() -> new ServiceException(zh_ch.FailedToDelete));
    }

    /**
     * 下载文档PDF
     *
     * @param parameters
     * @return
     */
    @PostMapping("/downloadDocumentation")
    public void downloadDocumentation(@RequestBody ClientParameters parameters, HttpServletResponse response) {
        docUserPermService.downloadDocumentation(parameters, response);
    }

}


